package top.ply.authservice.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;
import top.ply.authservice.service.impl.WechatAuthServiceImpl;
import top.ply.authservice.service.impl.WechatLoginWorkerImpl;
import top.ply.common_unit.entity.RespEntity;
import top.ply.common_unit.global_resp.RespUtil;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

@RestController
@RequestMapping("/wechat")
public class WechatAuthController {

    @Autowired
    @Qualifier("wechatAuthService")
    private WechatAuthServiceImpl wechatAuthService;

    @RequestMapping(value = "/login", method = {RequestMethod.POST})
    public RespEntity wechatLogin(String js_code, HttpServletResponse resp) {
        String token = wechatAuthService.wechatUserLogin(js_code);
        if (token == null) {
            Integer failReason = wechatAuthService.getFailReason();
            if (failReason.equals(WechatLoginWorkerImpl.ILLEGAL_PARAMETER)) {
                return RespUtil.illegalParameter();
            } else if (failReason.equals(WechatLoginWorkerImpl.USER_STATUS_ERROR)) {
                return RespUtil.userStatusError();
            } else {
                return RespUtil.baseFail();
            }
        } else {
            HashMap<String, Object> data = new HashMap<>();
            data.put("token", token);
            // 写入cookie
            resp.addCookie(new Cookie("token", token));
            return RespUtil.baseSuccess(data);
        }
    }

}
